package com.irun.pm.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.view.View;


/**
 * 图片压缩工具
 * 
 * @author Evy
 * 
 */
public class ImageUtil {
	public static final String IMAGE_PATH_BIG = "/sdcard/AliCC/images/";
	public static final String IMAGE_PATH_SMALL = "/sdcard/AliCC/images/small/";
	public static final String RECORD_PATH = "/sdcard/AliCC/recorder/";
	public static final String AVATARS_PATH = "/sdcard/AliCC/avatars/";
	/*
	 * 图片长宽相等
	 */
	public static final int BITMAP_SQUARE = 1;
	/*
	 * 纵向图片
	 */
	public static final int BITMAP_PORTRAIT = 2;
	/*
	 * 横向图片
	 */
	public static final int BITMAP_LANDSCAPE = 3;
	
	public static void setViewBounds(View view,int width,int height,int defaultWidth,int defaultHeight){
		if(width==-1){
			width = defaultWidth;
		}
		if(height==-1){
			height = defaultHeight;
		}
		android.view.ViewGroup.LayoutParams params = null;
		try {
			params = view.getLayoutParams();
			params.width = width;
			params.height  = height;
			view.setLayoutParams(params);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 保存图片
	 * 
	 * @param bitmap
	 * @param filePath
	 */
	public static void saveBmp(Bitmap bitmap, String filePath) {
		File file = new File(filePath);
		try {
			FileOutputStream out = new FileOutputStream(file);
			if (bitmap.compress(Bitmap.CompressFormat.JPEG, 80, out)) {
				out.flush();
				out.close();
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 保存图片
	 * 
	 * @param bitmap
	 * @param filePath
	 */
	public static void saveDrawBmp(Bitmap bitmap, String filePath) {
		File file = new File(filePath);
		try {
			FileOutputStream out = new FileOutputStream(file);
			if (bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out)) {
				out.flush();
				out.close();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 压缩图片并保存
	 * 
	 * @param bmp
	 * @param filePath
	 * @return
	 */
	public static boolean compressBitMap(String filePath, String fileName) {
		try {

			if ("".equals(filePath) || filePath == null) {
				return false;
			}

			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inJustDecodeBounds = true;
			// 获取这个图片的宽和高
			Bitmap bitmap = BitmapFactory.decodeFile(filePath, options); // 此时返回bm为空
			options.inJustDecodeBounds = false;
			// 原始图片大小
			int width = options.outWidth;
			int height = options.outHeight;
			options.inPreferredConfig = Bitmap.Config.RGB_565;
			options.inTempStorage = new byte[16 * 1024];
			options.inPurgeable = true;
			options.inInputShareable = true;
			int smallSampleSize = 1;
			int bigSampSize = 1;
			int max = width > height ? width : height;
			int pow = max / 1024;
			//bigSampSize = (int) Math.pow(2, pow);
			bigSampSize = computeSampleSize(options, -1, 512*512);
			System.out.println("bigSampSize=" + bigSampSize);
			smallSampleSize = bigSampSize * 2;
			System.out.println("smallSampleSize=" + smallSampleSize);
			options.inSampleSize = bigSampSize;
			bitmap = BitmapFactory.decodeFile(filePath, options);
			saveBmp(bitmap, IMAGE_PATH_BIG + fileName);
			bitmap.recycle();
			bitmap = null ;
			options.inSampleSize = smallSampleSize;
			bitmap = BitmapFactory.decodeFile(filePath, options);
			saveBmp(bitmap, IMAGE_PATH_SMALL + fileName);
			bitmap.recycle();
			bitmap = null ; 
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}catch (OutOfMemoryError e) {
			return false;
		}
	}

	/**
	 * 压缩涂鸦背景图片
	 * 
	 * @param bmp
	 * @param filePath
	 * @return Bitmap
	 */
	public static Bitmap compressScrawBitmap(String filePath, int screenWidth,
			int screenHight) {
		try {
			if (StringUtil.isEmpty(filePath)) {
				return null;
			}

			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inJustDecodeBounds = true;
			// 获取这个图片的宽和高
			Bitmap bitmap = BitmapFactory.decodeFile(filePath, options); // 此时返回bm为空
			options.inJustDecodeBounds = false;
			// 原始图片大小
			int bitmapWidth = options.outWidth;
			int bitmapHeight = options.outHeight;
			options.inPreferredConfig = Bitmap.Config.RGB_565;
			options.inTempStorage = new byte[16 * 1024];
			options.inPurgeable = true;
			options.inInputShareable = true;

			// 比例
			float scale = 1f;
			// 宽图
			if (bitmapWidth >= bitmapHeight) {
				if (bitmapWidth > screenWidth) {
					scale = (float) bitmapWidth / screenWidth;
					if (scale > (int) scale) {
						scale = (int) scale + 1;
					}
				}
				// 竖图
			} else {
				if (bitmapHeight > screenHight) {
					scale = (float) bitmapHeight / screenHight;
					if (scale > (int) scale) {
						scale = (int) scale + 1;
					}
				}
			}
			options.inSampleSize = (int) scale;
			bitmap = BitmapFactory.decodeFile(filePath, options);
//			saveDrawBmp(bitmap, "/sdcard/draw_temp.jpg");
			
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			// 得到输出流
			bitmap.compress(Bitmap.CompressFormat.PNG, 30, baos);
			// 转输入流
			InputStream isBm = new ByteArrayInputStream(baos.toByteArray());
			// Bitmap bmp = BitmapFactory.decodeFile("/sdcard/draw_temp.jpg");
			Bitmap bmp = BitmapFactory.decodeStream(isBm);
			bitmap.recycle();
			bitmap = null ;
			return bmp;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 压缩涂鸦文字
	 * 
	 * @param bmp
	 * @return
	 */
	public static Bitmap bmpForText(Bitmap bmp) {
		BitmapFactory.Options opt = new BitmapFactory.Options();
		opt.inPreferredConfig = Bitmap.Config.ARGB_8888;
		opt.inTempStorage = new byte[16 * 1024];
		opt.inPurgeable = true;
		opt.inInputShareable = true;
		opt.inSampleSize = 5;
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bmp.compress(Bitmap.CompressFormat.PNG, 100, baos);
		InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
		Bitmap resetBmp = zoomBitmap(BitmapFactory.decodeStream(inputStream,
				null, opt));
		return resetBmp;
	}

	/**
	 * 缩放图片指定大小
	 * 
	 * @param bitmap
	 * @return
	 */
	public static Bitmap zoomBitmap(Bitmap bitmap) {
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();
		Matrix matrix = new Matrix();
		float scaleWidht = 0.5f;
		float scaleHeight = 0.5f;
		matrix.postScale(scaleWidht, scaleHeight);
		Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, width, height,
				matrix, true);
		return newbmp;
	}

	/**
	 * 以最省内存的方式读取图片
	 * @param url
	 * @return
	 */
	public static Bitmap readBitmap(String url){
		try {
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inJustDecodeBounds = true;
			// 获取这个图片的宽和高
			BitmapFactory.decodeFile(url, options); // 此时返回bm为空
			
			options.inJustDecodeBounds = false;
			// 原始图片大小
			int width = options.outWidth;
			int height = options.outHeight;
			options.inPreferredConfig = Bitmap.Config.RGB_565;
			options.inTempStorage = new byte[16 * 1024];
			options.inPurgeable = true;
			options.inInputShareable = true;
			int smallSampleSize = 1;
			int bigSampSize = 1;
			int max = width > height ? width : height;
			int pow = max / 1000;
			bigSampSize = (int) Math.pow(2, pow);
			smallSampleSize = bigSampSize * 2;
			//options.inSampleSize = smallSampleSize;
			options.inSampleSize = computeSampleSize(options, -1, 512*512);
			Bitmap bitmap = BitmapFactory.decodeFile(url, options);
			return bitmap;
		} catch (OutOfMemoryError e) {
			e.printStackTrace();
			System.gc();
			return null;
		}
	}

	/**
	 * 以最省内存的方式读取图片
	 * 
	 * @param context
	 * @param resId
	 * @return
	 */
	public static Bitmap readBitMap(Context context, int resId) {
		BitmapFactory.Options opt = new BitmapFactory.Options();
		opt.inPreferredConfig = Bitmap.Config.ARGB_8888;
		opt.inTempStorage = new byte[16 * 1024];
		opt.inPurgeable = true;
		opt.inInputShareable = true;
		opt.inSampleSize = 2;
		// 获取资源图片
		InputStream is = context.getResources().openRawResource(resId);
		Bitmap bmp = BitmapFactory.decodeStream(is, null, opt);
		Matrix matrix = new Matrix();
		matrix.postScale(bmp.getWidth(), bmp.getHeight());
		Bitmap resetBmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp
				.getHeight(), matrix, true);
		bmp.recycle() ;
		bmp = null ;
		return resetBmp;
	}


	/**
	 * 保存头像
	 * 
	 * @param bitmap
	 * @param filePath
	 */
	public static void saveHeadBmp(Bitmap bitmap, String filePath) {
		File file = new File(filePath);
		try {
			FileOutputStream out = new FileOutputStream(file);
			if (bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out)) {
				out.flush();
				out.close();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 压缩头像图片并保存 100*100
	 * 
	 * @param bmp
	 * @param filePath
	 * @return
	 */
	public static Bitmap compressHeadBitMap(String filePath) {
		try {
			if (filePath == null || "".equals(filePath)) {
				return null;
			}
			int count = 2;
			BitmapFactory.Options options = new BitmapFactory.Options();
			 options.inJustDecodeBounds = true;
			 // 获取这个图片的宽和高
			 Bitmap tmp = BitmapFactory.decodeFile(filePath, options); //
//			 此时返回bm为空
			 options.inJustDecodeBounds = false;
			 // 原始图片大小
			 int bitmapWidth = options.outWidth;
			 count = bitmapWidth/100;
			 
			 options.inPreferredConfig = Bitmap.Config.RGB_565;
			 options.inTempStorage = new byte[16 * 1024];
			 options.inPurgeable = true;
			 options.inInputShareable = true;
			options.inSampleSize = count;
			Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);
			return bitmap;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public static int computeSampleSize(BitmapFactory.Options options,
	         int minSideLength, int maxNumOfPixels) {
	     int initialSize = computeInitialSampleSize(options, minSideLength,
	             maxNumOfPixels);
	 
	     int roundedSize;
	     if (initialSize <= 8) {
	         roundedSize = 1;
	         while (roundedSize < initialSize) {
	             roundedSize <<= 1;
	         }
	     } else {
	         roundedSize = (initialSize + 7) / 8 * 8;
	     }
	 
	     return roundedSize;
	 }
	 
	 private static int computeInitialSampleSize(BitmapFactory.Options options,
	         int minSideLength, int maxNumOfPixels) {
	     double w = options.outWidth;
	     double h = options.outHeight;
	 
	     int lowerBound = (maxNumOfPixels == -1) ? 1 :
	             (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));
	     int upperBound = (minSideLength == -1) ? 512 :
	             (int) Math.min(Math.floor(w / minSideLength),
	             Math.floor(h / minSideLength));
	 
	     if (upperBound < lowerBound) {
	         // return the larger one when there is no overlapping zone.
	         return lowerBound;
	     }
	 
	     if ((maxNumOfPixels == -1) &&
	             (minSideLength == -1)) {
	         return 1;
	     } else if (minSideLength == -1) {
	         return lowerBound;
	     } else {
	         return upperBound;
	     }
	 }
}

